import pymysql
import rsa
import sys
import os
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '../../')))

def insert_into_blockchain(table_name,data):
    config = {
        'host': '192.168.72.102',
        'user': 'test',
        'password': '123',
        'database': 'blockchain666',
        'port': 3306,
        'charset': 'utf8mb4',
        'cursorclass': pymysql.cursors.DictCursor
    }

    try:
        with pymysql.connect(**config) as conn:
            with conn.cursor() as cursor:
                columns = ','.join(data.keys())
                placeholders = ','.join(['%s'] * len(data))
                sql = f"insert into {table_name} ({columns}) values ({placeholders})"
                cursor.execute(sql,tuple(data.values()))
                conn.commit()
                return 1
    except Exception as e:
        print(f"DID区块链插入失败，错误为：{e}")
        return 0



def query_data(table_name,index,need_query_data_name):
    default_config = {
        'host': '192.168.72.102',
        'user': 'test',
        'password': '123',
        'database': 'blockchain666',
        'port': 3306,
        'charset': 'utf8mb4',
        'cursorclass': pymysql.cursors.DictCursor
    }
    try:
        #print(f"index:{index}")
        if len(index) != 1:
            raise ValueError("DID部分的区块链查询index只能包含一个字段")

        with pymysql.connect(**default_config) as conn:
            with conn.cursor() as cursor:
                column = next(iter(index.keys()))  # 获取唯一的键
                sql = f"select {need_query_data_name} from {table_name} where {column} = %s"
                # 执行查询（返回行数，但不直接使用）
                cursor.execute(sql, (index[column],))
                # 获取查询结果（单条）
                result = cursor.fetchone()
                #print(f"result:{result}")

                data=result[need_query_data_name]
                # result=data[0]
                return data
    except Exception as e:
        print(f"DID部分的区块链查询出错，错误是{e}")
        return 0

def query_group_key(group_id,self_id):
    default_config = {
        'host': '192.168.72.102',
        'user': 'test',
        'password': '123',
        'database': 'blockchain666',
        'port': 3306,
        'charset': 'utf8mb4',
        'cursorclass': pymysql.cursors.DictCursor
    }
    table_name = "group_key"

    try:
        with pymysql.connect(**default_config) as conn:
            with conn.cursor() as cursor:
                sql = f'select encryptGroupKey from {table_name} where groupId = %s and memberId = %s'
                cursor.execute(sql,(group_id,self_id))
                results = cursor.fetchall()
                return results[0]['encryptGroupKey'] if results else None
    except Exception as e:
        print(f'DID部分的区块链查询群密钥错误，错误为{e}')
        return 0

def query_temporary_PublicKey(my_id, other_id):
    default_config = {
        'host': '192.168.72.102',
        'user': 'test',
        'password': '123',
        'database': 'blockchain666',
        'port': 3306,
        'charset': 'utf8mb4',
        'cursorclass': pymysql.cursors.DictCursor
    }
    try:
        with pymysql.connect(** default_config) as conn:
            with conn.cursor() as cursor:
                # 使用 %s 作为占位符
                sql = 'select temporary_PublicKey from temporary_key_other_to_me where my_id = %s and other_id = %s'
                cursor.execute(sql, (my_id, other_id))
                results = cursor.fetchall()

                converted_data = {
                    'temporary_PublicKey': results[0]['temporary_PublicKey']
                }
                #print(f"eee:{converted_data}")
                public_key_str = converted_data['temporary_PublicKey']

                public_key_bytes = public_key_str.encode('utf-8')

                # 加载为rsa.PublicKey对象（适用于PKCS#1格式）
                public_key = rsa.PublicKey.load_pkcs1(public_key_bytes)
                return public_key
    except Exception as e:
        print(f"DID部分 查找临时公钥出错，错误为:{e}")
        return 0

def delete_repetitive_key(my_id,other_id):
    default_config = {
        'host': '192.168.72.102',
        'user': 'test',
        'password': '123',
        'database': 'blockchain666',
        'port': 3306,
        'charset': 'utf8mb4',
        'cursorclass': pymysql.cursors.DictCursor
    }
    try:
        with pymysql.connect(**default_config) as conn:
            with conn.cursor() as cursor:
                sql = 'delete from temporary_key_other_to_me where my_id = %s and other_id = %s'
                cursor.execute(sql, (my_id, other_id))
                conn.commit()
    except Exception as e:
        print(f"DID部分 区块链删除公钥出错！错误为{e}")



"""192.168.72.102"""

"""
临时公钥的表要改
"""


